package net.oschina.arvin.dbjava.model;

import net.oschina.arvin.dbjava.util.Utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 注释描述
 *
 * @author Arvin
 * @time 2017/9/30 11:28
 */
public class CommentDescriptor {

    /**
     * 注释类型
     */
    private enum Type {

        /**
         * 单行注释，如使用 //
         */
        SINGLE_LINE,

        /** 多行注释 */
        MULTI_LINE
    }

    /** 注释类型 */
    private Type type = null;

    /** 注释类型 */
    private List<String> commentTextList = new ArrayList<String>();

    /** 每一行文本 */
    private List<String> commentList = new ArrayList<String>();

    /** 注释参数和值 */
    private Map<String, List<String>> commentParamsMap = new HashMap<String, List<String>>();

    /**
     * 添加注释行
     *
     * @param line 注释行
     * @return 如果发现是新的注释，会返回新的注释对象
     */
    public CommentDescriptor append(String line) {
        if (Utils.isBlank(line)) {
            return this;
        }
        line = line.trim();
        if (type == null) {
            if (line.startsWith("/*")) {
                type = Type.MULTI_LINE;
            } else if (line.startsWith("//")) {
                type = Type.SINGLE_LINE;
                commentTextList.add(line.trim().replaceAll("^\\s*//", "").trim());
            }
            if (type != null) {
                commentList.add(line.trim());
                if (Type.MULTI_LINE == type) {
                    commentTextList.add(line.replaceAll("^\\s*/\\*+(.*)\\s*$", "$1").replaceAll("\\s*\\*+/\\s*$", "").trim());
                } else {
                    commentTextList.add(line.replaceAll("^\\s*//(.*)$", "$1").trim());
                }
            }
        } else {
            String tempLine = line.trim();
            if (tempLine.startsWith("/*")) {
                // 需要新的 CommentDescriptor
                CommentDescriptor cd = new CommentDescriptor();
                cd.append(tempLine);
                return cd;
            } else {
                commentList.add(tempLine);
                if (!line.endsWith("*/")) {
                    if (Type.MULTI_LINE == type) {
                        commentTextList.add(line.replaceAll("^\\s*/\\*+(.*)\\s*$", "$1").replaceAll("\\s*\\*+/\\s*$", "").trim());
                    } else {
                        commentTextList.add(line.replaceAll("^\\s*//(.*)$", "$1").trim());
                    }
                }
            }
        }
        return this;
    }

    public Type getType() {
        return type;
    }

    public List<String> getCommentTextList() {
        return commentTextList;
    }

    public List<String> getCommentList() {
        return commentList;
    }

    public Map<String, List<String>> getCommentParamsMap() {
        return commentParamsMap;
    }
}
